package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;
import com.ny.until.PasswordUntil;
import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<User> fillAllUser() {
        return userMapper.fillAllUser();
    }
    //登录
    @Override
    public User login(String username, String password) {return userMapper.login(username,password);}

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername( username);
    }

    @Override
    public int insertUser(User user) {
        //密码加密
        user.setCreated_time(new Date());
        String password = user.getPassword();
        String pwd = PasswordUntil.encryptPassword( password);
        user.setPassword(pwd);
        return userMapper.insertUser( user);
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail( email);
    }
    @Override
    public void sendEmailCode(String email) {

            //生成验证码
            String code = emailService.createCode();
            // 把验证码存储到redis数据中,进行验证和过期的
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            ops.set(email, code,10, java.util.concurrent.TimeUnit.MINUTES);
            emailService.sendEmail(email, code);

    }

    @Override
    public int updatePasswordByEmail(String email, String password) {
        //密码加密
        password = PasswordUntil.encryptPassword( password);
        return userMapper.updatePasswordByEmail(email, password);
    }

    @Override
    public boolean checkCode(String email, String code) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(email);
        if (redisCode != null && redisCode.equals(code)) {
            return true;
        }
        return false;
    }

    // 实现用户查询逻辑（密码MD5加密后比对）
    @Override
    public User findUser(String username, String password) {
        return userMapper.findUser(username, PasswordUntil.encryptPassword(password));
    }
}
